iT邦幫忙

2022 iThome 鐵人賽

DAY 30
0
Software Development

戀戀 Elixir系列 第 30

三十. Exceptions

  • 分享至 

  • xImage
  •  

While continuing your work at Instruments of Texas, there is progress being made on the Elixir implementation of the RPN calculator.

Your team would like to be able to raise errors that are more specific than the generic errors provided by the standard library. You are doing some research, but you have decided to implement two new errors which implement the Exception Behaviour.

1. Error for Division by Zero

Dividing a number by zero produces an undefined result, which the team decides is best represented by an error.

Implement the DivisionByZeroError module to have the error message: "division by zero occurred"

2. Error when encountering stack underflow

RPN calculators use a stack to keep track of numbers before they are added. The team represents this stack with a list of numbers (integer and floating-point), e.g.: [3, 4.0].
Each operation needs a specific number of numbers on the stack in order to perform its calculation. When there are not enough numbers on the stack, this is called a stack underflow error.
Implement the StackUnderflowError exception which provides a default message, and optional extra context

3. Write a dividing function

Implement the divide/1 function which takes a stack (list of numbers) and:

raises stack underflow when the stack does not contain enough numbers
raises division by zero when the divisor is 0 (note the stack of numbers is stored in the reverse order)
performs the division when no errors are raised


https://exercism.org/tracks/elixir/exercises/stack-underflow

defmodule RPNCalculator.Exception do
  @moduledoc """
  practice custom error
  """
  defmodule DivisionByZeroError do
    defexception message: "division by zero occurred"
  end

  defmodule StackUnderflowError do
    defexception message: "stack underflow occurred"

    @impl true
    def exception(custom_msg) do
      case custom_msg do
        [] -> %__MODULE__{}
        _ -> %__MODULE__{message: "stack underflow occurred, context: #{custom_msg}"}
      end
    end
  end

  def divide(value) when length(value) <= 1, do: raise raise StackUnderflowError, "when dividing"
  def divide([0, _]), do: raise DivisionByZeroError
  def divide([divider, number]), do: div(number, divider)
end

這三十天,自己基本上練習了一次 Elixir 基礎需要了解的語法與概念,確實與以往學 OOP 語言的感覺不同。
感謝猴子成員一起度過鐵人,感謝來了解 Elixir 的人,感謝平台提供挑戰,感謝 José Valim,感謝 Larry Tesler。


上一篇
二十九. Erlang Libraries & Randomness
系列文
戀戀 Elixir30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言